from django.db.models import Q
from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.pagination import PageNumberPagination
from django.core.cache import cache
from rest_framework.response import Response

from game.ser import CategorySerializer, GameSerializer
from game.models import GameCategory, Game


# Create your views here.


class MyPagination(PageNumberPagination):
    page_size = 1
    page_size_query_param = 'size'
    page_query_param = 'page'
    max_page_size = 10


class GameCategoryViewSet(viewsets.ModelViewSet):
    queryset = GameCategory.objects.all()
    serializer_class = CategorySerializer
    lookup_field = 'pk'
    lookup_url_kwarg = 'pk'


class GameViewSet(viewsets.ModelViewSet):
    queryset = Game.objects.all()
    serializer_class = GameSerializer
    lookup_field = 'pk'
    lookup_url_kwarg = 'pk'
    pagination_class = MyPagination

    def get_queryset(self):
        queryset = super().get_queryset()
        name = self.request.query_params.get('name')
        status = self.request.query_params.get('status')
        cate = self.request.query_params.get('category')
        query = Q()
        if name:
            query &= Q(name__icontains=name)
        if status:
            query &= Q(status=status)
        if cate:
            query &= Q(category=cate)
        return queryset.filter(query)

    @action(methods=['put'], detail=True)
    def update_status(self, request, pk):
        game = self.get_object()
        game.status = request.data.get('status')
        game.save()
        return Response(status=status.HTTP_200_OK)

    # @action(methods=['get'], detail=False)
    # def my_borrow_history(self, request):
    #     key = 'game:list'
    #     gameList = cache.get(key)
    #     if gameList:
    #         return Response({
    #             'code': 200,
    #             'msg': '请求成功',
    #             'data': gameList
    #         })
    #     gameList = Game.objects.filter(status=2)
    #     res = GameSerializer(gameList, many=True)
    #     if not res.data:
    #         cache.set(key, [], 60 * 60 * 24)
    #     cache.set(key, res.data, 60 * 60 * 24)
    #     return Response({
    #         'code': 200,
    #         'msg': '请求成功',
    #         'data': res.data
    #     })

